<template>
  <div class="after-sale-container">
    <div class="header">
      <a href="javascript:void(0)" @click="$router.go(-1)" class="back-button">
        <img src="./me-img/back.png" alt="返回" width="40%" height="100%" />
      </a>
      <img src="./me-img/logo.png" alt="logo" class="logo" />
    </div>

    <div class="body">
      <div class="after-sale-content">
        <h2 class="title">申请退换货</h2>

        <div class="product-info">
          <img :src="order.image" alt="商品图片" class="product-image" />
          <div class="product-details">
            <h4>{{ order.name }}</h4>
            <p>单价：{{ order.price }}￥</p>
            <p>数量: {{ order.quantity }}</p>
            <p class="product-allprice">
              总计: {{ (order.price * order.quantity).toFixed(2) }}￥
            </p>
          </div>
        </div>

        <div class="form-section">
          <div class="form-group">
            <label>服务类型</label>
            <div class="radio-group">
              <label class="radio-label">
                <input type="radio" v-model="serviceType" value="return" />
                <span>退货</span>
              </label>
              <label class="radio-label">
                <input type="radio" v-model="serviceType" value="exchange" />
                <span>换货</span>
              </label>
            </div>
          </div>

          <div class="form-group">
            <label>{{
              serviceType === "return" ? "退款原因" : "换货原因"
            }}</label>
            <select v-model="reason" class="form-control">
              <option value="">
                请选择{{ serviceType === "return" ? "退款" : "换货" }}原因
              </option>
              <option value="quality">质量问题</option>
              <option value="wrong">发错货</option>
              <option value="description">与描述不符</option>
              <option value="size">尺码不合适</option>
              <option value="color">颜色不符</option>
              <option value="other">其他原因</option>
            </select>
          </div>

          <div class="form-group" v-if="reason === 'other'">
            <label>其他原因说明</label>
            <textarea
              v-model="otherReason"
              class="form-control"
              placeholder="请详细说明您的{{ serviceType === 'return' ? '退款' : '换货' }}原因"
            ></textarea>
          </div>

          <div class="form-group" v-if="serviceType === 'return'">
            <label>退款金额</label>
            <input
              type="text"
              :value="refundAmount"
              class="form-control"
              readonly
            />
          </div>

          <div class="form-group" v-if="serviceType === 'exchange'">
            <label>换货商品</label>
            <select v-model="exchangeProduct" class="form-control">
              <option value="">请选择要更换的商品</option>
              <option value="same">同款商品</option>
              <option value="other">其他商品</option>
            </select>
          </div>

          <div
            class="form-group"
            v-if="serviceType === 'exchange' && exchangeProduct === 'other'"
          >
            <label>新商品名称</label>
            <input
              type="text"
              v-model="newProductName"
              class="form-control"
              placeholder="请输入要更换的商品名称"
            />
          </div>

          <div class="form-group">
            <label>问题描述</label>
            <textarea
              v-model="problemDescription"
              class="form-control"
              :placeholder="
                serviceType === 'return'
                  ? '请详细描述商品存在的问题'
                  : '请详细描述需要换货的原因和要求'
              "
            ></textarea>
          </div>

          <div class="form-group">
            <label>上传凭证</label>
            <div class="upload-area">
              <input
                type="file"
                id="upload"
                style="display: none"
                @change="handleFileUpload"
                multiple
                accept="image/*"
              />
              <label for="upload" class="upload-btn">+ 添加图片</label>
              <div class="preview-container">
                <div
                  v-for="(file, index) in uploadedFiles"
                  :key="index"
                  class="preview-item"
                >
                  <img :src="file.preview" alt="凭证图片" />
                  <span class="remove-btn" @click="removeFile(index)">×</span>
                </div>
              </div>
              <p class="upload-tips">最多可上传9张图片，支持JPG/PNG格式</p>
            </div>
          </div>
        </div>

        <div class="action-buttons">
          <button class="cancel-btn" @click="$router.go(-1)">取消</button>
          <button class="submit-btn" @click="submitAfterSale">
            {{ serviceType === "return" ? "提交退货申请" : "提交换货申请" }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import orderData from "./me.json";
export default {
  name: "AfterSale",
  data() {
    return {
      order: {
        id: parseInt(this.$route.query.orderId) || "",
        image: this.$route.query.image || "https://via.placeholder.com/80",
        name: this.$route.query.name || "",
        price: parseFloat(this.$route.query.price) || 0,
        quantity: parseInt(this.$route.query.quantity) || 1,
        specs: this.$route.query.specs || "",
        status: this.$route.query.status || "pendingDelivery",
      },
      serviceType: "return",
      reason: "",
      otherReason: "",
      exchangeProduct: "",
      newProductName: "",
      problemDescription: "",
      uploadedFiles: [],
      maxFiles: 9,
    };
  },
  computed: {
    refundAmount() {
      return (this.order.price * this.order.quantity).toFixed(2);
    },
  },
  created() {
    this.loadSavedFormData();
  },
  methods: {
    loadSavedFormData() {
      const savedForms = JSON.parse(
        localStorage.getItem("afterSaleForms") || "{}"
      );
      const savedForm = savedForms[this.order.id];
      if (savedForm) {
        Object.keys(savedForm).forEach((key) => {
          if (key in this.$data) {
            this[key] = savedForm[key];
          }
        });
      }
    },
    saveFormData() {
      const savedForms = JSON.parse(
        localStorage.getItem("afterSaleForms") || "{}"
      );
      savedForms[this.order.id] = {
        serviceType: this.serviceType,
        reason: this.reason,
        otherReason: this.otherReason,
        exchangeProduct: this.exchangeProduct,
        newProductName: this.newProductName,
        problemDescription: this.problemDescription,
        uploadedFiles: this.uploadedFiles,
      };
      localStorage.setItem("afterSaleForms", JSON.stringify(savedForms));
    },
    handleFileUpload(event) {
      const files = event.target.files;
      const remainingSlots = this.maxFiles - this.uploadedFiles.length;

      if (remainingSlots <= 0) {
        alert(`最多只能上传${this.maxFiles}张图片`);
        return;
      }

      const filesToAdd = Math.min(files.length, remainingSlots);
      for (let i = 0; i < filesToAdd; i++) {
        const file = files[i];
        if (file.type.match("image.*")) {
          const reader = new FileReader();
          reader.onload = (e) => {
            this.uploadedFiles.push({
              file: file,
              preview: e.target.result,
            });
            this.saveFormData();
          };
          reader.readAsDataURL(file);
        }
      }
    },
    removeFile(index) {
      this.uploadedFiles.splice(index, 1);
      this.saveFormData();
    },
    async submitAfterSale() {
      console.log("submitAfterSale called");

      try {
        // 验证逻辑
        if (!this.reason) {
          alert(`请选择${this.serviceType === "return" ? "退款" : "换货"}原因`);
          return;
        }
        if (this.reason === "other" && !this.otherReason) {
          alert("请填写其他原因说明");
          return;
        }
        if (this.serviceType === "exchange" && !this.exchangeProduct) {
          alert("请选择换货商品");
          return;
        }
        if (
          this.serviceType === "exchange" &&
          this.exchangeProduct === "other" &&
          !this.newProductName
        ) {
          alert("请输入要更换的商品名称");
          return;
        }
        if (!this.problemDescription) {
          alert("请填写问题描述");
          return;
        }

        console.log("All validations passed");

        // 保存表单数据
        this.saveFormData();

        // 获取并更新订单
        let orderList = JSON.parse(localStorage.getItem("orderList")) || [
          ...orderData.products,
        ];
        const newStatus =
          this.serviceType === "return" ? "returning" : "exchanging";
        const orderIndex = orderList.findIndex(
          (item) => item.id === this.order.id
        );

        if (orderIndex !== -1) {
          // 创建新对象
          const updatedOrder = {
            ...orderList[orderIndex],
            status: newStatus,
          };

          // 更新数组
          orderList = [
            ...orderList.slice(0, orderIndex),
            updatedOrder,
            ...orderList.slice(orderIndex + 1),
          ];

          // 保存更新后的订单列表
          localStorage.setItem("orderList", JSON.stringify(orderList));
          console.log("Order status updated in localStorage");

          // 触发storage事件
          window.dispatchEvent(new Event("storage"));

          alert(`${this.serviceType === "return" ? "退货" : "换货"}申请已提交`);

          // 确保路由跳转执行
          await this.$nextTick();
          this.$router.push({
            path: "/order-list",
            query: {
              tab: "afterSale",
              _t: Date.now(), // 添加时间戳确保每次都是新路由
            },
          });
        } else {
          console.error("Order not found in orderList");
          alert("找不到对应的订单");
        }
      } catch (error) {
        console.error("Error in submitAfterSale:", error);
        alert("提交过程中发生错误，请查看控制台");
      }
    },
  },
};
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
}

.after-sale-container {
  min-height: 100vh;
  background-color: #ffffff;
  min-width: 1000px;
  overflow-x: auto;
}

.header {
  background-color: #f4efd2;
  height: 50px;
  align-items: center;
  box-shadow: #bdbbb7 0px 2px 8px;
  padding: 2px 0px;
}

.header,
.body {
  width: 60%;
  margin: 0px auto;
  overflow: hidden;
  display: flex;
}

.body {
  margin: 30px auto;
  min-height: 700px;
  background-color: #ffffff;
}

.logo {
  width: 10%;
  height: auto;
  margin-left: auto;
}

.back-button {
  color: #333;
  display: flex;
  width: 10%;
  height: 100%;
  text-decoration: none;
  line-height: 40px;
  overflow: hidden;
}

.after-sale-content {
  width: 100%;
  padding: 20px;
  background-color: #f4efd2;
  border-radius: 10px;
  box-shadow: #bdbbb7 0px 0px 5px;
}

.title {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
}

.product-info {
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: white;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: #bdbbb7 0px 0px 3px;
}

.product-image {
  width: 120px;
  height: 120px;
  border-radius: 5px;
  margin-right: 20px;
  object-fit: cover;
}

.product-details {
  flex: 1;
}

.product-details h4 {
  margin-bottom: 10px;
  font-size: 18px;
  color: #333;
}

.product-details p {
  margin: 8px 0;
  font-size: 14px;
  color: #666;
}

.product-specs {
  color: #888;
  font-size: 13px;
  margin: 10px 0;
}

.product-allprice {
  font-size: 18px;
  color: rgb(237, 129, 51);
  font-weight: bold;
  margin-top: 10px;
}

.form-section {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: #bdbbb7 0px 0px 3px;
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: bold;
  color: #333;
}

.radio-group {
  display: flex;
  gap: 20px;
}

.radio-label {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.radio-label input {
  margin-right: 8px;
}

.form-control {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

textarea.form-control {
  min-height: 100px;
  resize: vertical;
}

.upload-area {
  margin-top: 10px;
}

.upload-btn {
  display: inline-block;
  padding: 8px 15px;
  background-color: #d9c596;
  color: #333;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  margin-bottom: 10px;
  transition: background-color 0.3s;
}

.upload-btn:hover {
  background-color: #c5b082;
}

.preview-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.preview-item {
  position: relative;
  width: 80px;
  height: 80px;
  border: 1px dashed #ddd;
  border-radius: 4px;
  overflow: hidden;
}

.preview-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.remove-btn {
  position: absolute;
  top: -5px;
  right: -5px;
  width: 20px;
  height: 20px;
  background-color: #ff4d4f;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 12px;
  line-height: 1;
}

.upload-tips {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 20px;
}

.cancel-btn,
.submit-btn {
  padding: 12px 40px;
  border: none;
  border-radius: 5px;
  font-size: 16px;
  cursor: pointer;
  box-shadow: #bdbbb7 0px 0px 3px;
  transition: opacity 0.3s;
}

.cancel-btn {
  background-color: #d9c596;
  color: #333;
}

.submit-btn {
  background-color: rgb(237, 129, 51);
  color: white;
}

.cancel-btn:hover,
.submit-btn:hover {
  opacity: 0.9;
}
</style>
